import {
  indexApi
} from '../../api/index';
import {
  request
} from '../../utils/request';
Page({
  data: {
    defaultData: {
      title: "我的消息", // 导航栏标题
      // imageSrc: "/images/home.png",
      isBackToPreviousPage: false
    },
    isEmpty: false,//消息是否为空
    tabs: ['系统消息', '服务消息'],
    activeIndex: 1,
    pageNum: 0,
    pageSize: 10,
    messages: {   
    }
  },

  onShow(){
    wx.switchTab({
      url: '/pages/quickOrder/index',
    });
    this.getAllNews()
    this.checkToken()
  },

  // 检查有没有token
  checkToken(){
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({
        isLogin:true
      })
      console.log("token",token);
      console.log("isLogin",this.data.isLogin);
    } else {
      this.setData({
        isLogin:false
      })
      console.log("token=====",token);
      console.log("isLogin=======",this.data.isLogin);
    }
  },

  async getAllNews(){
    const reqTemplate={
      pageNum:this.data.pageNum,
      pageSize:this.data.pageSize
    }
    try {
      const res = await request({
        url: indexApi.allNews(),
        method: "POST",
        data: reqTemplate
      });
      console.log("getAllNews",res.data);
      if (res.data.length == 0) {
        console.log("为空");
        this.setData({
          isEmpty: false
        });
      } else {
        this.setData({
          isEmpty: true
        });
      }
      this.setData({
        messages: res.data
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

  clickNews(event){
    console.log("event",event.currentTarget.dataset.isread);
    const isread=event.currentTarget.dataset.isread
    if (isread !=1) {
      this.clearNews(isread)
    }
  },

  async clearNews(isread) {
    // const reqTemplate=noticeMessageId
    const reqTemplate={
      noticeMessageId:isread
    }
    try {
      const res = await request({
        url: indexApi.clearNews(),
        method: "POST",
        data: reqTemplate     
      });
      console.log(res);
     this.getAllNews
    } catch (error) {
      console.error("Error:", error);
    }
  },

  async clearAllNews(){
    try {
      const res = await request({
        url: indexApi.clearAllNews(),
        data: {
        }
      });
      console.log("clearAllNews",res); 
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //切换消息
  onTextClick(event) {
    const noticetypeId = event.currentTarget.dataset.noticetypeid;
    console.log("noticetypeId",noticetypeId);
    this.setData({
      activeIndex: noticetypeId
    });
  },

  toLogin(){
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },

  // 分享给朋友
  onShareAppMessage: function () {
    return {
      title: '方案报价',
      path: '/pages/news/index', 
     
    };
  },

  // 分享到朋友圈
  onShareTimeline: function () {
    return {
      title: '方案报价', 
      query: '' 
    };
  }
})